package com.limh.jkzs.activity

import android.annotation.SuppressLint
import android.support.v4.view.ViewPager
import android.view.KeyEvent
import android.widget.Toast
import com.limh.blehelper.Ble2Manager
import com.limh.jkzs.R
import com.limh.jkzs.adapter.FragmentAdapter
import com.limh.jkzs.base.BaseActivity
import com.limh.jkzs.base.BaseFragment
import com.limh.jkzs.fragment.BlueFragment
import com.limh.jkzs.fragment.WifiFragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity() {
    private val fragments = mutableListOf<BaseFragment>()
    private var adapter: FragmentAdapter? = null

    override fun findViews() {
        setContentView(R.layout.activity_main)
    }

    override fun initView() {
        fragments.add(BlueFragment())
        fragments.add(WifiFragment())
        adapter = FragmentAdapter(supportFragmentManager, fragments)
        vpMain.adapter = adapter
        vpMain.currentItem = 0
        vpMain.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            @SuppressLint("SetTextI18n")
            override fun onPageScrollStateChanged(state: Int) {
                if (state == 2) {
                    when (vpMain.currentItem) {
                        0 -> {

                        }
                        1 -> {

                        }
                    }
                }
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {

            }

        })
    }

    private var exitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(applicationContext, "再按一次退出程序",
                        Toast.LENGTH_SHORT).show()
                exitTime = System.currentTimeMillis()
            } else {
                finish()
                System.exit(0)
            }
        }
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        Ble2Manager.getInstance().destory()
    }
}
